<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace suifeng\builder\form\validator;

use suifeng\builder\form\Validator;

class Compare extends Validator
{
    /**
     * 比较逻辑。
     * @var unknown
     */
    public $logic;

    /**
     * 比较的值。
     * @var unknown
     */
    public $value;

    /**
     * 默认的比较信息。
     *
     * @var array
     */
    protected $default_messages = [
        'eq'    =>  '{control.label} 必须等于 {value}。',
        'ne'    =>  '{control.label} 必须不等于 {value}。',
        'gt'    =>  '{control.label} 必须大于 {value}。',
        'egt'   =>  '{control.label} 必须大于或等于 {value}。',
        'lt'    =>  '{control.label} 必须小于 {value}。',
        'elt'   =>  '{control.label} 必须小于或等于 {value}。',
    ];

    /**
     * 验证方法。
     */
    protected function _validate_core()
    {
        $value = $this->_get_control_value();

        switch (strtolower($this->logic)) {
            case 'eq':
            case '=':
            case '==':
                $logic = 'eq';
                $result = $value > $this->value;
                break;

            case 'neq':
            case '<>':
            case '!=':
                $logic = 'neq';
                $result = $value <> $this->value;
                break;

            case 'lt':
            case '<':
                $logic = 'lt';
                $result = $value < $this->value;
                break;

            case 'elt':
            case '<=':
                $logic = 'elt';
                $result = $value <= $this->value;
                break;

            case 'gt':
            case '>':
                $logic = 'gt';
                $result = $value > $this->value;
                break;

            case 'egt':
            case '>=':
                $logic = 'egt';
                $result = $value >= $this->value;
                break;

            default:
                return;
        }

        if ($result === false) {
            $message = $this->message ? $this->message : $this->default_messages[$logic];
            $this->errors[] = $this->_format_message($message);
        }
    }
}
